{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "JndnmDMp66FL"
      },
      "source": [
        "#### Copyright 2017 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "both",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "hMqWDc_m6rUC"
      },
      "outputs": [],
      "source": [
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "eV16J6oUY-HN",
        "slideshow": {
          "slide_type": "slide"
        }
      },
      "source": [
        "# Improving Neural Net Performance"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "0Rwl1iXIKxkm"
      },
      "source": [
        "**Learning Objective:** Improve the performance of a neural network by normalizing features and applying various optimization algorithms\n",
        "\n",
        "**NOTE:** The optimization methods described in this exercise are not specific to neural networks; they are effective means to improve most types of models."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "lBPTONWzKxkn"
      },
      "source": [
        "## Setup\n",
        "\n",
        "First, we'll load the data."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "VtYVuONUKxko"
      },
      "outputs": [],
      "source": [
        "from __future__ import print_function\n",
        "\n",
        "import math\n",
        "\n",
        "from IPython import display\n",
        "from matplotlib import cm\n",
        "from matplotlib import gridspec\n",
        "from matplotlib import pyplot as plt\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "from sklearn import metrics\n",
        "import tensorflow as tf\n",
        "from tensorflow.python.data import Dataset\n",
        "\n",
        "tf.logging.set_verbosity(tf.logging.ERROR)\n",
        "pd.options.display.max_rows = 10\n",
        "pd.options.display.float_format = '{:.1f}'.format\n",
        "\n",
        "california_housing_dataframe = pd.read_csv(\"https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv\", sep=\",\")\n",
        "\n",
        "california_housing_dataframe = california_housing_dataframe.reindex(\n",
        "    np.random.permutation(california_housing_dataframe.index))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "B8qC-jTIKxkr"
      },
      "outputs": [],
      "source": [
        "def preprocess_features(california_housing_dataframe):\n",
        "  \"\"\"Prepares input features from California housing data set.\n",
        "\n",
        "  Args:\n",
        "    california_housing_dataframe: A Pandas DataFrame expected to contain data\n",
        "      from the California housing data set.\n",
        "  Returns:\n",
        "    A DataFrame that contains the features to be used for the model, including\n",
        "    synthetic features.\n",
        "  \"\"\"\n",
        "  selected_features = california_housing_dataframe[\n",
        "    [\"latitude\",\n",
        "     \"longitude\",\n",
        "     \"housing_median_age\",\n",
        "     \"total_rooms\",\n",
        "     \"total_bedrooms\",\n",
        "     \"population\",\n",
        "     \"households\",\n",
        "     \"median_income\"]]\n",
        "  processed_features = selected_features.copy()\n",
        "  # Create a synthetic feature.\n",
        "  processed_features[\"rooms_per_person\"] = (\n",
        "    california_housing_dataframe[\"total_rooms\"] /\n",
        "    california_housing_dataframe[\"population\"])\n",
        "  return processed_features\n",
        "\n",
        "def preprocess_targets(california_housing_dataframe):\n",
        "  \"\"\"Prepares target features (i.e., labels) from California housing data set.\n",
        "\n",
        "  Args:\n",
        "    california_housing_dataframe: A Pandas DataFrame expected to contain data\n",
        "      from the California housing data set.\n",
        "  Returns:\n",
        "    A DataFrame that contains the target feature.\n",
        "  \"\"\"\n",
        "  output_targets = pd.DataFrame()\n",
        "  # Scale the target to be in units of thousands of dollars.\n",
        "  output_targets[\"median_house_value\"] = (\n",
        "    california_housing_dataframe[\"median_house_value\"] / 1000.0)\n",
        "  return output_targets"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "Ah6LjMIJ2spZ"
      },
      "outputs": [],
      "source": [
        "# Choose the first 12000 (out of 17000) examples for training.\n",
        "training_examples = preprocess_features(california_housing_dataframe.head(12000))\n",
        "training_targets = preprocess_targets(california_housing_dataframe.head(12000))\n",
        "\n",
        "# Choose the last 5000 (out of 17000) examples for validation.\n",
        "validation_examples = preprocess_features(california_housing_dataframe.tail(5000))\n",
        "validation_targets = preprocess_targets(california_housing_dataframe.tail(5000))\n",
        "\n",
        "# Double-check that we've done the right thing.\n",
        "print(\"Training examples summary:\")\n",
        "display.display(training_examples.describe())\n",
        "print(\"Validation examples summary:\")\n",
        "display.display(validation_examples.describe())\n",
        "\n",
        "print(\"Training targets summary:\")\n",
        "display.display(training_targets.describe())\n",
        "print(\"Validation targets summary:\")\n",
        "display.display(validation_targets.describe())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "NqIbXxx222ea"
      },
      "source": [
        "## Train the Neural Network\n",
        "\n",
        "Next, we'll train the neural network."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "6k3xYlSg27VB"
      },
      "outputs": [],
      "source": [
        "def construct_feature_columns(input_features):\n",
        "  \"\"\"Construct the TensorFlow Feature Columns.\n",
        "\n",
        "  Args:\n",
        "    input_features: The names of the numerical input features to use.\n",
        "  Returns:\n",
        "    A set of feature columns\n",
        "  \"\"\" \n",
        "  return set([tf.feature_column.numeric_column(my_feature)\n",
        "              for my_feature in input_features])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "De9jwyy4wTUT"
      },
      "outputs": [],
      "source": [
        "def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):\n",
        "    \"\"\"Trains a neural network model.\n",
        "  \n",
        "    Args:\n",
        "      features: pandas DataFrame of features\n",
        "      targets: pandas DataFrame of targets\n",
        "      batch_size: Size of batches to be passed to the model\n",
        "      shuffle: True or False. Whether to shuffle the data.\n",
        "      num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely\n",
        "    Returns:\n",
        "      Tuple of (features, labels) for next data batch\n",
        "    \"\"\"\n",
        "    \n",
        "    # Convert pandas data into a dict of np arrays.\n",
        "    features = {key:np.array(value) for key,value in dict(features).items()}                                           \n",
        " \n",
        "    # Construct a dataset, and configure batching/repeating.\n",
        "    ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit\n",
        "    ds = ds.batch(batch_size).repeat(num_epochs)\n",
        "    \n",
        "    # Shuffle the data, if specified.\n",
        "    if shuffle:\n",
        "      ds = ds.shuffle(10000)\n",
        "    \n",
        "    # Return the next batch of data.\n",
        "    features, labels = ds.make_one_shot_iterator().get_next()\n",
        "    return features, labels"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "W-51R3yIKxk4"
      },
      "outputs": [],
      "source": [
        "def train_nn_regression_model(\n",
        "    my_optimizer,\n",
        "    steps,\n",
        "    batch_size,\n",
        "    hidden_units,\n",
        "    training_examples,\n",
        "    training_targets,\n",
        "    validation_examples,\n",
        "    validation_targets):\n",
        "  \"\"\"Trains a neural network regression model.\n",
        "  \n",
        "  In addition to training, this function also prints training progress information,\n",
        "  as well as a plot of the training and validation loss over time.\n",
        "  \n",
        "  Args:\n",
        "    my_optimizer: An instance of `tf.train.Optimizer`, the optimizer to use.\n",
        "    steps: A non-zero `int`, the total number of training steps. A training step\n",
        "      consists of a forward and backward pass using a single batch.\n",
        "    batch_size: A non-zero `int`, the batch size.\n",
        "    hidden_units: A `list` of int values, specifying the number of neurons in each layer.\n",
        "    training_examples: A `DataFrame` containing one or more columns from\n",
        "      `california_housing_dataframe` to use as input features for training.\n",
        "    training_targets: A `DataFrame` containing exactly one column from\n",
        "      `california_housing_dataframe` to use as target for training.\n",
        "    validation_examples: A `DataFrame` containing one or more columns from\n",
        "      `california_housing_dataframe` to use as input features for validation.\n",
        "    validation_targets: A `DataFrame` containing exactly one column from\n",
        "      `california_housing_dataframe` to use as target for validation.\n",
        "      \n",
        "  Returns:\n",
        "    A tuple `(estimator, training_losses, validation_losses)`:\n",
        "      estimator: the trained `DNNRegressor` object.\n",
        "      training_losses: a `list` containing the training loss values taken during training.\n",
        "      validation_losses: a `list` containing the validation loss values taken during training.\n",
        "  \"\"\"\n",
        "\n",
        "  periods = 10\n",
        "  steps_per_period = steps / periods\n",
        "  \n",
        "  # Create a DNNRegressor object.\n",
        "  my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n",
        "  dnn_regressor = tf.estimator.DNNRegressor(\n",
        "      feature_columns=construct_feature_columns(training_examples),\n",
        "      hidden_units=hidden_units,\n",
        "      optimizer=my_optimizer\n",
        "  )\n",
        "  \n",
        "  # Create input functions.\n",
        "  training_input_fn = lambda: my_input_fn(training_examples, \n",
        "                                          training_targets[\"median_house_value\"], \n",
        "                                          batch_size=batch_size)\n",
        "  predict_training_input_fn = lambda: my_input_fn(training_examples, \n",
        "                                                  training_targets[\"median_house_value\"], \n",
        "                                                  num_epochs=1, \n",
        "                                                  shuffle=False)\n",
        "  predict_validation_input_fn = lambda: my_input_fn(validation_examples, \n",
        "                                                    validation_targets[\"median_house_value\"], \n",
        "                                                    num_epochs=1, \n",
        "                                                    shuffle=False)\n",
        "\n",
        "  # Train the model, but do so inside a loop so that we can periodically assess\n",
        "  # loss metrics.\n",
        "  print(\"Training model...\")\n",
        "  print(\"RMSE (on training data):\")\n",
        "  training_rmse = []\n",
        "  validation_rmse = []\n",
        "  for period in range (0, periods):\n",
        "    # Train the model, starting from the prior state.\n",
        "    dnn_regressor.train(\n",
        "        input_fn=training_input_fn,\n",
        "        steps=steps_per_period\n",
        "    )\n",
        "    # Take a break and compute predictions.\n",
        "    training_predictions = dnn_regressor.predict(input_fn=predict_training_input_fn)\n",
        "    training_predictions = np.array([item['predictions'][0] for item in training_predictions])\n",
        "    \n",
        "    validation_predictions = dnn_regressor.predict(input_fn=predict_validation_input_fn)\n",
        "    validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])\n",
        "    \n",
        "    # Compute training and validation loss.\n",
        "    training_root_mean_squared_error = math.sqrt(\n",
        "        metrics.mean_squared_error(training_predictions, training_targets))\n",
        "    validation_root_mean_squared_error = math.sqrt(\n",
        "        metrics.mean_squared_error(validation_predictions, validation_targets))\n",
        "    # Occasionally print the current loss.\n",
        "    print(\"  period %02d : %0.2f\" % (period, training_root_mean_squared_error))\n",
        "    # Add the loss metrics from this period to our list.\n",
        "    training_rmse.append(training_root_mean_squared_error)\n",
        "    validation_rmse.append(validation_root_mean_squared_error)\n",
        "  print(\"Model training finished.\")\n",
        "\n",
        "  # Output a graph of loss metrics over periods.\n",
        "  plt.ylabel(\"RMSE\")\n",
        "  plt.xlabel(\"Periods\")\n",
        "  plt.title(\"Root Mean Squared Error vs. Periods\")\n",
        "  plt.tight_layout()\n",
        "  plt.plot(training_rmse, label=\"training\")\n",
        "  plt.plot(validation_rmse, label=\"validation\")\n",
        "  plt.legend()\n",
        "\n",
        "  print(\"Final RMSE (on training data):   %0.2f\" % training_root_mean_squared_error)\n",
        "  print(\"Final RMSE (on validation data): %0.2f\" % validation_root_mean_squared_error)\n",
        "\n",
        "  return dnn_regressor, training_rmse, validation_rmse"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "KueReMZ9Kxk7"
      },
      "outputs": [],
      "source": [
        "_ = train_nn_regression_model(\n",
        "    my_optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.0007),\n",
        "    steps=5000,\n",
        "    batch_size=70,\n",
        "    hidden_units=[10, 10],\n",
        "    training_examples=training_examples,\n",
        "    training_targets=training_targets,\n",
        "    validation_examples=validation_examples,\n",
        "    validation_targets=validation_targets)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "flxmFt0KKxk9"
      },
      "source": [
        "## Linear Scaling\n",
        "It can be a good standard practice to normalize the inputs to fall within the range -1, 1. This helps SGD not get stuck taking steps that are too large in one dimension, or too small in another. Fans of numerical optimization may note that there's a connection to the idea of using a preconditioner here."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "Dws5rIQjKxk-"
      },
      "outputs": [],
      "source": [
        "def linear_scale(series):\n",
        "  min_val = series.min()\n",
        "  max_val = series.max()\n",
        "  scale = (max_val - min_val) / 2.0\n",
        "  return series.apply(lambda x:((x - min_val) / scale) - 1.0)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "MVmuHI76N2Sz",
        "slideshow": {
          "slide_type": "slide"
        }
      },
      "source": [
        "## Task 1: Normalize the Features Using Linear Scaling\n",
        "\n",
        "**Normalize the inputs to the scale -1, 1.**\n",
        "\n",
        "**Spend about 5 minutes training and evaluating on the newly normalized data.  How well can you do?**\n",
        "\n",
        "As a rule of thumb, NN's train best when the input features are roughly on the same scale.\n",
        "\n",
        "Sanity check your normalized data.  (What would happen if you forgot to normalize one feature?)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "yD948ZgAM6Cx"
      },
      "outputs": [],
      "source": [
        "def normalize_linear_scale(examples_dataframe):\n",
        "  \"\"\"Returns a version of the input `DataFrame` that has all its features normalized linearly.\"\"\"\n",
        "  #\n",
        "  # Your code here: normalize the inputs.\n",
        "  #\n",
        "  pass\n",
        "\n",
        "normalized_dataframe = normalize_linear_scale(preprocess_features(california_housing_dataframe))\n",
        "normalized_training_examples = normalized_dataframe.head(12000)\n",
        "normalized_validation_examples = normalized_dataframe.tail(5000)\n",
        "\n",
        "_ = train_nn_regression_model(\n",
        "    my_optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.0007),\n",
        "    steps=5000,\n",
        "    batch_size=70,\n",
        "    hidden_units=[10, 10],\n",
        "    training_examples=normalized_training_examples,\n",
        "    training_targets=training_targets,\n",
        "    validation_examples=normalized_validation_examples,\n",
        "    validation_targets=validation_targets)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "jFfc3saSxg6t"
      },
      "source": [
        "### Solution\n",
        "\n",
        "Click below for one possible solution."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Ax_IIQVRx4gr"
      },
      "source": [
        "Since normalization uses min and max, we have to ensure it's done on the entire dataset at once. \n",
        "\n",
        "We can do that here because all our data is in a single DataFrame. If we had multiple data sets, a good practice would be to derive the normalization parameters from the training set and apply those identically to the test set."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "D-bJBXrJx-U_"
      },
      "outputs": [],
      "source": [
        "def normalize_linear_scale(examples_dataframe):\n",
        "  \"\"\"Returns a version of the input `DataFrame` that has all its features normalized linearly.\"\"\"\n",
        "  processed_features = pd.DataFrame()\n",
        "  processed_features[\"latitude\"] = linear_scale(examples_dataframe[\"latitude\"])\n",
        "  processed_features[\"longitude\"] = linear_scale(examples_dataframe[\"longitude\"])\n",
        "  processed_features[\"housing_median_age\"] = linear_scale(examples_dataframe[\"housing_median_age\"])\n",
        "  processed_features[\"total_rooms\"] = linear_scale(examples_dataframe[\"total_rooms\"])\n",
        "  processed_features[\"total_bedrooms\"] = linear_scale(examples_dataframe[\"total_bedrooms\"])\n",
        "  processed_features[\"population\"] = linear_scale(examples_dataframe[\"population\"])\n",
        "  processed_features[\"households\"] = linear_scale(examples_dataframe[\"households\"])\n",
        "  processed_features[\"median_income\"] = linear_scale(examples_dataframe[\"median_income\"])\n",
        "  processed_features[\"rooms_per_person\"] = linear_scale(examples_dataframe[\"rooms_per_person\"])\n",
        "  return processed_features\n",
        "\n",
        "normalized_dataframe = normalize_linear_scale(preprocess_features(california_housing_dataframe))\n",
        "normalized_training_examples = normalized_dataframe.head(12000)\n",
        "normalized_validation_examples = normalized_dataframe.tail(5000)\n",
        "\n",
        "_ = train_nn_regression_model(\n",
        "    my_optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.005),\n",
        "    steps=2000,\n",
        "    batch_size=50,\n",
        "    hidden_units=[10, 10],\n",
        "    training_examples=normalized_training_examples,\n",
        "    training_targets=training_targets,\n",
        "    validation_examples=normalized_validation_examples,\n",
        "    validation_targets=validation_targets)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "MrwtdStNJ6ZQ",
        "slideshow": {
          "slide_type": "slide"
        }
      },
      "source": [
        "## Task 2: Try a Different Optimizer\n",
        "\n",
        "** Use the Adagrad and Adam optimizers and compare performance.**\n",
        "\n",
        "The Adagrad optimizer is one alternative. The key insight of Adagrad is that it modifies the learning rate adaptively for each coefficient in a model, monotonically lowering the effective learning rate.  This works great for convex problems, but isn't always ideal for the non-convex problem Neural Net training.  You can use Adagrad by specifying `AdagradOptimizer` instead of `GradientDescentOptimizer`.  Note that you may need to use a larger learning rate with Adagrad.\n",
        "\n",
        "For non-convex optimization problems, Adam is sometimes more efficient than Adagrad.  To use Adam, invoke the `tf.train.AdamOptimizer` method. This method takes several optional hyperparameters as arguments, but our solution only specifies one of these (`learning_rate`). In a production setting, you should specify and tune the optional hyperparameters carefully."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "61GSlDvF7-7q"
      },
      "outputs": [],
      "source": [
        "#\n",
        "# YOUR CODE HERE: Retrain the network using Adagrad and then Adam.\n",
        "#"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "FSPZIiYgyh93"
      },
      "source": [
        "### Solution\n",
        "\n",
        "Click below for the solution"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "X1QcIeiKyni4"
      },
      "source": [
        "First, let's try Adagrad."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "Ntn4jJxnypGZ"
      },
      "outputs": [],
      "source": [
        "_, adagrad_training_losses, adagrad_validation_losses = train_nn_regression_model(\n",
        "    my_optimizer=tf.train.AdagradOptimizer(learning_rate=0.5),\n",
        "    steps=500,\n",
        "    batch_size=100,\n",
        "    hidden_units=[10, 10],\n",
        "    training_examples=normalized_training_examples,\n",
        "    training_targets=training_targets,\n",
        "    validation_examples=normalized_validation_examples,\n",
        "    validation_targets=validation_targets)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "5JUsCdRRyso3"
      },
      "source": [
        "Now let's try Adam."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "lZB8k0upyuY8"
      },
      "outputs": [],
      "source": [
        "_, adam_training_losses, adam_validation_losses = train_nn_regression_model(\n",
        "    my_optimizer=tf.train.AdamOptimizer(learning_rate=0.009),\n",
        "    steps=500,\n",
        "    batch_size=100,\n",
        "    hidden_units=[10, 10],\n",
        "    training_examples=normalized_training_examples,\n",
        "    training_targets=training_targets,\n",
        "    validation_examples=normalized_validation_examples,\n",
        "    validation_targets=validation_targets)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "twYgC8FGyxm6"
      },
      "source": [
        "Let's print a graph of loss metrics side by side."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "8RHIUEfqyzW0"
      },
      "outputs": [],
      "source": [
        "plt.ylabel(\"RMSE\")\n",
        "plt.xlabel(\"Periods\")\n",
        "plt.title(\"Root Mean Squared Error vs. Periods\")\n",
        "plt.plot(adagrad_training_losses, label='Adagrad training')\n",
        "plt.plot(adagrad_validation_losses, label='Adagrad validation')\n",
        "plt.plot(adam_training_losses, label='Adam training')\n",
        "plt.plot(adam_validation_losses, label='Adam validation')\n",
        "_ = plt.legend()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "UySPl7CAQ28C",
        "slideshow": {
          "slide_type": "slide"
        }
      },
      "source": [
        "## Task 3: Explore Alternate Normalization Methods\n",
        "\n",
        "**Try alternate normalizations for various features to further improve performance.**\n",
        "\n",
        "If you look closely at summary stats for your transformed data, you may notice that linear scaling some features leaves them clumped close to `-1`.\n",
        "\n",
        "For example, many features have a median of `-0.8` or so, rather than `0.0`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "QWmm_6CGKxlH"
      },
      "outputs": [],
      "source": [
        "_ = normalized_training_examples.hist(bins=20, figsize=(18, 12), xlabelsize=10)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Xx9jgEMHKxlJ"
      },
      "source": [
        "We might be able to do better by choosing additional ways to transform these features.\n",
        "\n",
        "For example, a log scaling might help some features.  Or clipping extreme values may make the remainder of the scale more informative."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "baKZa6MEKxlK"
      },
      "outputs": [],
      "source": [
        "def log_normalize(series):\n",
        "  return series.apply(lambda x:math.log(x+1.0))\n",
        "\n",
        "def clip(series, clip_to_min, clip_to_max):\n",
        "  return series.apply(lambda x:(\n",
        "    min(max(x, clip_to_min), clip_to_max)))\n",
        "\n",
        "def z_score_normalize(series):\n",
        "  mean = series.mean()\n",
        "  std_dv = series.std()\n",
        "  return series.apply(lambda x:(x - mean) / std_dv)\n",
        "\n",
        "def binary_threshold(series, threshold):\n",
        "  return series.apply(lambda x:(1 if x \u003e threshold else 0))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "-wCCq_ClKxlO"
      },
      "source": [
        "The block above contains a few additional possible normalization functions. Try some of these, or add your own.\n",
        "\n",
        "Note that if you normalize the target, you'll need to un-normalize the predictions for loss metrics to be comparable."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "8ToG-mLfMO9P"
      },
      "outputs": [],
      "source": [
        "def normalize(examples_dataframe):\n",
        "  \"\"\"Returns a version of the input `DataFrame` that has all its features normalized.\"\"\"\n",
        "  #\n",
        "  # YOUR CODE HERE: Normalize the inputs.\n",
        "  #\n",
        "  pass\n",
        "\n",
        "normalized_dataframe = normalize(preprocess_features(california_housing_dataframe))\n",
        "normalized_training_examples = normalized_dataframe.head(12000)\n",
        "normalized_validation_examples = normalized_dataframe.tail(5000)\n",
        "\n",
        "_ = train_nn_regression_model(\n",
        "    my_optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.0007),\n",
        "    steps=5000,\n",
        "    batch_size=70,\n",
        "    hidden_units=[10, 10],\n",
        "    training_examples=normalized_training_examples,\n",
        "    training_targets=training_targets,\n",
        "    validation_examples=normalized_validation_examples,\n",
        "    validation_targets=validation_targets)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "GhFtWjQRzD2l"
      },
      "source": [
        "### Solution\n",
        "\n",
        "Click below for one possible solution."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "OMoIsUMmzK9b"
      },
      "source": [
        "These are only a few ways in which we could think about the data. Other transformations may work even better!\n",
        "\n",
        "`households`, `median_income` and `total_bedrooms` all appear normally-distributed in a log space.\n",
        "\n",
        "`latitude`, `longitude` and `housing_median_age` would probably be better off just scaled linearly, as before.\n",
        "\n",
        "`population`, `totalRooms` and `rooms_per_person` have a few extreme outliers. They seem too extreme for log normalization to help. So let's clip them instead."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "XDEYkPquzYCH"
      },
      "outputs": [],
      "source": [
        "def normalize(examples_dataframe):\n",
        "  \"\"\"Returns a version of the input `DataFrame` that has all its features normalized.\"\"\"\n",
        "  processed_features = pd.DataFrame()\n",
        "\n",
        "  processed_features[\"households\"] = log_normalize(examples_dataframe[\"households\"])\n",
        "  processed_features[\"median_income\"] = log_normalize(examples_dataframe[\"median_income\"])\n",
        "  processed_features[\"total_bedrooms\"] = log_normalize(examples_dataframe[\"total_bedrooms\"])\n",
        "  \n",
        "  processed_features[\"latitude\"] = linear_scale(examples_dataframe[\"latitude\"])\n",
        "  processed_features[\"longitude\"] = linear_scale(examples_dataframe[\"longitude\"])\n",
        "  processed_features[\"housing_median_age\"] = linear_scale(examples_dataframe[\"housing_median_age\"])\n",
        "\n",
        "  processed_features[\"population\"] = linear_scale(clip(examples_dataframe[\"population\"], 0, 5000))\n",
        "  processed_features[\"rooms_per_person\"] = linear_scale(clip(examples_dataframe[\"rooms_per_person\"], 0, 5))\n",
        "  processed_features[\"total_rooms\"] = linear_scale(clip(examples_dataframe[\"total_rooms\"], 0, 10000))\n",
        "\n",
        "  return processed_features\n",
        "\n",
        "normalized_dataframe = normalize(preprocess_features(california_housing_dataframe))\n",
        "normalized_training_examples = normalized_dataframe.head(12000)\n",
        "normalized_validation_examples = normalized_dataframe.tail(5000)\n",
        "\n",
        "_ = train_nn_regression_model(\n",
        "    my_optimizer=tf.train.AdagradOptimizer(learning_rate=0.15),\n",
        "    steps=1000,\n",
        "    batch_size=50,\n",
        "    hidden_units=[10, 10],\n",
        "    training_examples=normalized_training_examples,\n",
        "    training_targets=training_targets,\n",
        "    validation_examples=normalized_validation_examples,\n",
        "    validation_targets=validation_targets)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "b7atJTbzU9Ca",
        "slideshow": {
          "slide_type": "slide"
        }
      },
      "source": [
        "## Optional Challenge: Use only Latitude and Longitude Features\n",
        "\n",
        "**Train a NN model that uses only latitude and longitude as features.**\n",
        "\n",
        "Real estate people are fond of saying that location is the only important feature in housing price.\n",
        "Let's see if we can confirm this by training a model that uses only latitude and longitude as features.\n",
        "\n",
        "This will only work well if our NN can learn complex nonlinearities from latitude and longitude.\n",
        "\n",
        "**NOTE:** We may need a network structure that has more layers than were useful earlier in the exercise."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "T5McjahpamOc"
      },
      "outputs": [],
      "source": [
        "#\n",
        "# YOUR CODE HERE: Train the network using only latitude and longitude\n",
        "#"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "P8BLQ7T71JWd"
      },
      "source": [
        "### Solution\n",
        "\n",
        "Click below for a possible solution."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "1hwaFCE71OPZ"
      },
      "source": [
        "It's a good idea to keep latitude and longitude normalized:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "djKtt4mz1ZEc"
      },
      "outputs": [],
      "source": [
        "def location_location_location(examples_dataframe):\n",
        "  \"\"\"Returns a version of the input `DataFrame` that keeps only the latitude and longitude.\"\"\"\n",
        "  processed_features = pd.DataFrame()\n",
        "  processed_features[\"latitude\"] = linear_scale(examples_dataframe[\"latitude\"])\n",
        "  processed_features[\"longitude\"] = linear_scale(examples_dataframe[\"longitude\"])\n",
        "  return processed_features\n",
        "\n",
        "lll_dataframe = location_location_location(preprocess_features(california_housing_dataframe))\n",
        "lll_training_examples = lll_dataframe.head(12000)\n",
        "lll_validation_examples = lll_dataframe.tail(5000)\n",
        "\n",
        "_ = train_nn_regression_model(\n",
        "    my_optimizer=tf.train.AdagradOptimizer(learning_rate=0.05),\n",
        "    steps=500,\n",
        "    batch_size=50,\n",
        "    hidden_units=[10, 10, 5, 5, 5],\n",
        "    training_examples=lll_training_examples,\n",
        "    training_targets=training_targets,\n",
        "    validation_examples=lll_validation_examples,\n",
        "    validation_targets=validation_targets)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Dw2Mr9JZ1cRi"
      },
      "source": [
        "This isn't too bad for just two features. Of course, property values can still vary significantly within short distances."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "JndnmDMp66FL",
        "jFfc3saSxg6t",
        "FSPZIiYgyh93",
        "GhFtWjQRzD2l",
        "P8BLQ7T71JWd"
      ],
      "default_view": {},
      "name": "improving_neural_net_performance.ipynb",
      "provenance": [],
      "version": "0.3.2",
      "views": {}
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
